package com.mobdev.notepad.shared;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public abstract class AbstractNotepadProvider extends ContentProvider {



	protected static final String DATABASE_NAME = "notepad.db";
    protected static final String NOTES_TABLE_NAME = "notes";


    private static final int NOTES = 1;
    private static final int NOTE_ID = 2;

    
	private Uri NOTEPAD_URI = Uri.parse("content://" + getAuthority() + "/notes");

    private UriMatcher sUriMatcher;

    protected static HashMap<String, String> sNotesProjectionMap;

    private SQLiteOpenHelper mOpenHelper;

    
    protected abstract SQLiteOpenHelper getSQLiteOpenHelper();

    protected abstract String getContentType();

    protected abstract String getContentItemType();

	protected abstract String getAuthority();
	

    @Override
    public boolean onCreate() 
    {
        mOpenHelper = getSQLiteOpenHelper();
        
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(getAuthority(), "notes", NOTES);
        sUriMatcher.addURI(getAuthority(), "notes/#", NOTE_ID);

        return true;
    }


        
    

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
            String sortOrder) {
    	
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

        switch (sUriMatcher.match(uri)) {
        case NOTES:
            qb.setTables(NOTES_TABLE_NAME);
            qb.setProjectionMap(sNotesProjectionMap);
            break;

        case NOTE_ID:
            qb.setTables(NOTES_TABLE_NAME);
            qb.setProjectionMap(sNotesProjectionMap);
            qb.appendWhere(DBConstants._ID + "=" + uri.getPathSegments().get(1));
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        // If no sort order is specified use the default
        String orderBy;
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = DBConstants.DEFAULT_SORT_ORDER;
        } else {
            orderBy = sortOrder;
        }

        // Get the database and run the query
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);

        // Tell the cursor what uri to watch, so it knows when its source data changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }

    @Override
    public String getType(Uri uri) {
        switch (sUriMatcher.match(uri)) {
        case NOTES:
            return getContentType();

        case NOTE_ID:
            return getContentItemType();
            

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }


	@Override
    public Uri insert(Uri uri, ContentValues initialValues) {
        // Validate the requested uri
        if (sUriMatcher.match(uri) != NOTES) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }

        int now = (int) (System.currentTimeMillis()/1000);

        // Make sure that the fields are all set        
        if (values.containsKey(DBConstants.REMOTE_ID) == false) 
        	values.put(DBConstants.REMOTE_ID, "-1");
        
        if (values.containsKey(DBConstants.TITLE) == false) 
            values.put(DBConstants.TITLE, Resources.getSystem().getString(android.R.string.untitled));

        if (values.containsKey(DBConstants.CONTENTS) == false) 
            values.put(DBConstants.CONTENTS, "");

        if (values.containsKey(DBConstants.TAGS) == false) 
            values.put(DBConstants.TAGS, "");
        
        if (values.containsKey(DBConstants.CREATED_ON) == false)
        	values.put(DBConstants.CREATED_ON, now);
        
        if (values.containsKey(DBConstants.MODIFIED_ON) == false)
        	values.put(DBConstants.MODIFIED_ON, now);
        
        if (values.containsKey(DBConstants.SYNCED_ON) == false)
        	values.put(DBConstants.SYNCED_ON, 0); //not synced yet
        
        if (values.containsKey(DBConstants.NEW_NOTE_CREATED_ON_PHONE) == false)
        	values.put(DBConstants.NEW_NOTE_CREATED_ON_PHONE, 1);
        
        if (values.containsKey(DBConstants.DELETED_FROM_PHONE) == false)
        	values.put(DBConstants.DELETED_FROM_PHONE, 0);

        if (values.containsKey(DBConstants.DONT_SYNC_THIS_NOTE) == false)
        	values.put(DBConstants.DONT_SYNC_THIS_NOTE, 0);
        
        
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        long rowId = db.insert(NOTES_TABLE_NAME, DBConstants.CONTENTS, values);
        if (rowId > 0) {
            Uri noteUri = ContentUris.withAppendedId(NOTEPAD_URI, rowId);
            getContext().getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
    }

    @Override
    public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
    	
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
        case NOTES:
            count = db.update(NOTES_TABLE_NAME, values, where, whereArgs);
            break;

        case NOTE_ID:
            String noteId = uri.getPathSegments().get(1);
            count = db.update(NOTES_TABLE_NAME, values, DBConstants._ID + "=" + noteId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }
    
    @Override
    public int delete(Uri uri, String where, String[] whereArgs) {
    	//delete the note
    	SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
        case NOTES:
            count = db.delete(NOTES_TABLE_NAME, where, whereArgs);
            break;

        case NOTE_ID:
            String noteId = uri.getPathSegments().get(1);
            count = db.delete(NOTES_TABLE_NAME, DBConstants._ID + "=" + noteId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;        
    }
    

    static {

        sNotesProjectionMap = new HashMap<String, String>();
        sNotesProjectionMap.put(DBConstants._ID, DBConstants._ID);
        sNotesProjectionMap.put(DBConstants.REMOTE_ID, DBConstants.REMOTE_ID);
        sNotesProjectionMap.put(DBConstants.TITLE, DBConstants.TITLE);
        sNotesProjectionMap.put(DBConstants.CONTENTS, DBConstants.CONTENTS);
        sNotesProjectionMap.put(DBConstants.TAGS, DBConstants.TAGS);
        sNotesProjectionMap.put(DBConstants.CREATED_ON, DBConstants.CREATED_ON);
        sNotesProjectionMap.put(DBConstants.MODIFIED_ON, DBConstants.MODIFIED_ON);
        sNotesProjectionMap.put(DBConstants.SYNCED_ON, DBConstants.SYNCED_ON);
        sNotesProjectionMap.put(DBConstants.NEW_NOTE_CREATED_ON_PHONE, DBConstants.NEW_NOTE_CREATED_ON_PHONE);
        sNotesProjectionMap.put(DBConstants.DELETED_FROM_PHONE, DBConstants.DELETED_FROM_PHONE);
        sNotesProjectionMap.put(DBConstants.DONT_SYNC_THIS_NOTE, DBConstants.DONT_SYNC_THIS_NOTE);
    }
}
